Saving `test` results in a variable

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • iLL
    New Member
    • Oct 2006
    • 63

    Saving `test` results in a variable

    Is there any way to save the result of a "test" command in a variable, or would I have to do something like:

    bool=`if [ -d . ]; then echo 1; else echo 0; fi;`
  • michaelb
    Recognized Expert Contributor
    • Nov 2006
    • 534

    #2
    Shell already does it for you.
    In Bourne shell the result of the last executed command is saved in variable $?
    In C shell it's a built-in variable called status.

    Here's the sample script:

    Code:
    #!/bin/sh
    [ -d `pwd` ] 
    echo $?
    # the statement above should print 0, (success status) 
    # because your current directory is obviously a directory.
    
    [ -d /dev/nonsence ] 
    echo $?
    # the statement above will likely to print 1 (failure), 
    # it's unlikely that this directory exists
    Note that 0 is always a success, but shell may return other failure codes,
    so most often you're only interested to see whether you gor 0 or not:

    exec some shell command, then test the result:
    if [ "$?" -ne 0 ] ; then
    ... ...

    It is a common practice to include $? in double-quotes, as shown above.
    Hope it helps.

    Comment

    Working...